<template>
  <div class="inventory-management">
    <!-- 统计概览 -->
    <InventoryStats :stats="stats" />
    
    <!-- 筛选条件 -->
    <InventoryFilter 
      :query-params="queryParams"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 智能提醒 -->
    <InventorySmartAlerts 
      :inventory-items="inventoryItems"
      @alert-click="handleAlertClick"
    />
    
    <!-- 库存列表 -->
    <InventoryTable
      :inventory-items="inventoryItems"
      :loading="loading"
      :summary="summary"
      :pagination="pagination"
      :selected-items="selectedItems"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      @view-detail="viewInventoryDetail"
      @more-action="handleMoreAction"
    />
    
    <!-- 操作对话框 -->
    <InventoryOperationDialog
      v-model="showDialog"
      :editing-item="editingInventory"
      :products="products"
      @submit="saveInventory"
      @close="handleDialogClose"
    />
    
    <!-- 详情对话框 -->
    <InventoryDetailDialog
      v-model="detailDialogVisible"
      :item="detailItem"
      @close="handleDetailDialogClose"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  Box, Warning, DocumentDelete, Refresh, Upload, Operation, 
  Download, Plus, Setting, Sort, Edit, Document, ArrowDown 
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

// 导入API
import * as inventoryAPI from '@/api/inventory'

// 导入拆分的组件
import InventoryStats from './components/InventoryStats.vue'
import InventoryFilter from './components/InventoryFilter.vue'
import InventoryTable from './components/InventoryTable.vue'
import InventoryOperationDialog from './components/InventoryOperationDialog.vue'
import InventoryDetailDialog from './components/InventoryDetailDialog.vue'
import InventorySmartAlerts from './components/InventorySmartAlerts.vue'

// 数据模型
interface Product {
  id: number
  sku: string
  name: string
  specification: string
  unit: string
}

interface InventoryItem {
  id: number
  productId: number
  sku: string
  productName: string
  specification: string
  currentStock: number
  minStock: number
  maxStock: number
  unit: string
  lastUpdate: string
  status: string
  remark: string
}

interface InventorySummary {
  productCount: number
  totalValue: number
  warningCount: number
  outOfStockCount: number
}

interface QueryParams {
  productName: string
  sku: string
  status: string
  minStock: number | undefined
  maxStock: number | undefined
  updateDateRange: string[]
  page: number
  limit: number
}

// 响应式数据
const products = ref<Product[]>([
  {
    id: 1,
    sku: 'SKU001',
    name: '高性能计算服务器',
    specification: 'Intel Xeon, 64GB RAM, 2TB SSD',
    unit: '台'
  },
  {
    id: 2,
    sku: 'SKU002',
    name: '企业级存储阵列',
    specification: '24盘位, 128GB缓存',
    unit: '台'
  }
])

const inventoryItems = ref<InventoryItem[]>([])
const loading = ref(false)
const syncing = ref(false)
const showDialog = ref(false)
const detailDialogVisible = ref(false)
const detailItem = ref<InventoryItem | null>(null)
const editingInventory = ref<InventoryItem | null>(null)
const selectedItems = ref<InventoryItem[]>([])

const queryParams = reactive<QueryParams>({
  productName: '',
  sku: '',
  status: '',
  minStock: undefined,
  maxStock: undefined,
  updateDateRange: [],
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 计算属性
const stats = computed(() => {
  return {
    productCount: inventoryItems.value.length,
    totalValue: inventoryItems.value.reduce((sum: number, item: InventoryItem) => sum + item.currentStock * 10000, 0),
    warningCount: inventoryItems.value.filter((item: InventoryItem) => item.status === 'warning').length,
    outOfStockCount: inventoryItems.value.filter((item: InventoryItem) => item.status === 'out_of_stock').length,
    productTrend: 0,
    valueTrend: 0,
    warningTrend: 0,
    outOfStockTrend: 0
  }
})

const summary = computed<InventorySummary>(() => {
  return {
    productCount: inventoryItems.value.length,
    totalValue: inventoryItems.value.reduce((sum: number, item: InventoryItem) => sum + item.currentStock * 10000, 0),
    warningCount: inventoryItems.value.filter((item: InventoryItem) => item.status === 'warning').length,
    outOfStockCount: inventoryItems.value.filter((item: InventoryItem) => item.status === 'out_of_stock').length
  }
})

// 方法
const loadInventory = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      name: queryParams.productName,
      sku: queryParams.sku,
      status: queryParams.status,
      minStock: queryParams.minStock,
      maxStock: queryParams.maxStock
    }
    
    const response = await inventoryAPI.getProducts(params)
    
    if (response.success) {
      // 转换产品数据为库存数据格式
      inventoryItems.value = response.data.list.map((product: any) => ({
        id: product.id,
        productId: product.id,
        sku: product.sku,
        productName: product.name,
        specification: product.specification,
        currentStock: product.stock,
        minStock: product.minStock,
        maxStock: product.minStock * 2, // 简单计算最大库存为最小库存的2倍
        unit: product.unit,
        lastUpdate: product.updatedAt,
        status: product.stock <= product.minStock ? 'warning' : 
                product.stock === 0 ? 'out_of_stock' : 'sufficient',
        remark: product.description || ''
      }))
      
      pagination.total = response.data.pagination.total
      
      // 添加加载完成通知
      ElNotification({
        title: '加载完成',
        message: `成功加载 ${inventoryItems.value.length} 条库存记录`,
        type: 'success',
        duration: 2000
      })
    } else {
      ElMessage.error(response.message || '加载库存列表失败')
    }
  } catch (error) {
    ElMessage.error('加载库存列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const showInventoryDialog = () => {
  editingInventory.value = null
  showDialog.value = true
  ElNotification({
    title: '新增库存',
    message: '请填写库存信息',
    type: 'info',
    duration: 2000
  })
}

const editInventory = (inventory: InventoryItem) => {
  editingInventory.value = inventory
  showDialog.value = true
  // ElNotification({
  //   title: '编辑库存',
  //   message: `正在编辑 ${inventory.productName}`,
  //   type: 'info',
  //   duration: 2000
  // })
}

const viewInventoryDetail = (inventory: InventoryItem) => {
  detailItem.value = inventory
  detailDialogVisible.value = true
  // ElNotification({
  //   title: '查看详情',
  //   message: `查看 ${inventory.productName} 详情`,
  //   type: 'info',
  //   duration: 2000
  // })
}

const saveInventory = async (formData: any) => {
  try {
    // 检查是否是库存调整操作
    if (formData.adjustType && editingInventory.value) {
      // 执行库存调整
      const adjustParams = {
        productId: editingInventory.value.productId,
        adjustType: formData.adjustType,
        adjustAmount: formData.adjustAmount,
        reason: formData.adjustReason,
        remark: formData.remark
      }
      
      const response = await inventoryAPI.adjustInventory(adjustParams)
      
      if (response.success) {
        ElMessage.success('库存调整成功')
        loadInventory()
      } else {
        ElMessage.error(response.message || '库存调整失败')
        return
      }
    } else if (editingInventory.value) {
      // 编辑产品记录
      const updateData = {
        name: formData.productName,
        sku: formData.sku,
        specification: formData.specification,
        unit: formData.unit,
        stock: formData.currentStock,
        minStock: formData.minStock,
        description: formData.remark,
        categoryId: null,
        brandId: null,
        salePrice: 0,
        costPrice: 0
      }
      
      const response = await inventoryAPI.updateProduct(editingInventory.value.productId, updateData)
      
      if (response.success) {
        ElMessage.success('产品记录更新成功')
        loadInventory()
      } else {
        ElMessage.error(response.message || '更新产品记录失败')
        return
      }
    } else {
      // 新增产品记录
      const createData = {
        name: formData.productName,
        sku: formData.sku,
        specification: formData.specification,
        unit: formData.unit,
        stock: formData.currentStock,
        minStock: formData.minStock,
        description: formData.remark,
        status: 'active',
        categoryId: null,
        brandId: null,
        salePrice: 0,
        costPrice: 0
      }
      
      const response = await inventoryAPI.createProduct(createData)
      
      if (response.success) {
        ElMessage.success('产品记录添加成功')
        loadInventory()
      } else {
        ElMessage.error(response.message || '添加产品记录失败')
        return
      }
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + (error as Error).message)
  }
}

const handleDialogClose = () => {
  showDialog.value = false
  editingInventory.value = null
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  detailItem.value = null
}

const handleSearch = () => {
  ElMessage.info('筛选库存')
  loadInventory()
  ElNotification({
    title: '搜索',
    message: '正在搜索库存记录...',
    type: 'info',
    duration: 2000
  })
}

const handleReset = () => {
  Object.assign(queryParams, {
    productName: '',
    sku: '',
    status: '',
    minStock: undefined,
    maxStock: undefined,
    updateDateRange: []
  })
  loadInventory()
  ElNotification({
    title: '重置',
    message: '搜索条件已重置',
    type: 'info',
    duration: 2000
  })
}

const exportInventory = () => {
  // 模拟导出过程
  ElMessage.info('正在导出库存数据...')
  
  // 模拟导出完成
  setTimeout(() => {
    ElMessage.success('导出库存成功')
    ElNotification({
      title: '导出',
      message: '库存数据已导出',
      type: 'success',
      duration: 2000
    })
    
    // 这里可以添加实际的导出逻辑，比如生成CSV文件并下载
    // 例如：
    // const csvContent = generateCSV(inventoryItems.value)
    // downloadCSV(csvContent, 'inventory-export.csv')
  }, 1000)
}

const handleSyncInventory = () => {
  syncing.value = true
  ElMessage.info('开始同步库存数据...')
  ElNotification({
    title: '同步',
    message: '正在同步库存数据...',
    type: 'info',
    duration: 2000
  })
  // 模拟同步过程
  setTimeout(() => {
    syncing.value = false
    ElMessage.success('库存同步完成')
    loadInventory()
    ElNotification({
      title: '同步完成',
      message: '库存数据同步成功',
      type: 'success',
      duration: 2000
    })
  }, 2000)
}

const showImportDialog = () => {
  ElMessageBox.alert('请选择要导入的库存文件', '导入库存', {
    confirmButtonText: '确定'
  })
  ElNotification({
    title: '导入',
    message: '请选择要导入的库存文件',
    type: 'info',
    duration: 2000
  })
}

// 入库操作
const handleInbound = () => {
  ElMessageBox.prompt('请输入入库数量', '入库操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,  // 只允许正整数
    inputErrorMessage: '请输入有效的数量'
  }).then(({ value }) => {
    ElMessage.success(`成功入库 ${value} 件商品`)
    loadInventory()  // 重新加载库存数据
  }).catch(() => {
    ElMessage.info('取消入库操作')
  })
}

// 出库操作
const handleOutbound = () => {
  ElMessageBox.prompt('请输入出库数量', '出库操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,  // 只允许正整数
    inputErrorMessage: '请输入有效的数量'
  }).then(({ value }) => {
    ElMessage.success(`成功出库 ${value} 件商品`)
    loadInventory()  // 重新加载库存数据
  }).catch(() => {
    ElMessage.info('取消出库操作')
  })
}

// 调拨操作
const handleTransfer = () => {
  ElMessageBox.prompt('请输入调拨数量', '调拨操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,  // 只允许正整数
    inputErrorMessage: '请输入有效的数量'
  }).then(({ value }) => {
    ElMessageBox.prompt('请输入目标仓库', '调拨操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入目标仓库名称'
    }).then(({ value: targetWarehouse }) => {
      ElMessage.success(`成功调拨 ${value} 件商品到 ${targetWarehouse}`)
      loadInventory()  // 重新加载库存数据
    }).catch(() => {
      ElMessage.info('取消调拨操作')
    })
  }).catch(() => {
    ElMessage.info('取消调拨操作')
  })
}

const showBatchOperations = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要操作的库存记录')
    return
  }
  
  ElMessageBox.confirm(
    `您已选择 ${selectedItems.value.length} 条库存记录，是否执行批量操作？`,
    '批量操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里可以添加实际的批量操作逻辑
    // 例如：批量调整库存、批量导出等
    ElMessage.success(`成功对 ${selectedItems.value.length} 条记录执行批量操作`)
    // 清空选择
    selectedItems.value = []
  }).catch(() => {
    ElMessage.info('已取消批量操作')
  })
}

const handleSelectionChange = (selection: InventoryItem[]) => {
  selectedItems.value = selection
  if (selection.length > 0) {
    ElNotification({
      title: '已选择',
      message: `已选择 ${selection.length} 条记录`,
      type: 'info',
      duration: 2000
    })
  }
}

const handleRowClick = (row: InventoryItem) => {
  viewInventoryDetail(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  ElMessage.info(`按 ${sort.prop} ${sort.order} 排序`)
}

const handleSort = (field: string) => {
  ElMessage.info(`按 ${field} 排序`)
}

const handleMoreAction = (command: { action: string, row?: InventoryItem }) => {
  switch (command.action) {
    case 'edit':
      if (command.row) {
        editInventory(command.row)
      }
      break
    case 'history':
      if (command.row) {
        viewInventoryDetail(command.row)
      }
      break
    case 'adjust':
      if (command.row) {
        adjustInventory(command.row)
      }
      break
    case 'import':
      showImportDialog()
      break
    case 'export':
      exportInventory()
      break
    case 'inbound':
      handleInbound()
      break
    case 'outbound':
      handleOutbound()
      break
    case 'transfer':
      handleTransfer()
      break
    case 'sync':
      handleSyncInventory()
      break
    case 'batch':
      showBatchOperations()
      break
  }
}

// 添加库存调整方法
const adjustInventory = (inventory: InventoryItem) => {
  editingInventory.value = inventory
  showDialog.value = true
  ElNotification({
    title: '库存调整',
    message: `正在调整 ${inventory.productName} 的库存`,
    type: 'info',
    duration: 2000
  })
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  loadInventory()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadInventory()
}

const showColumnSettings = () => {
  ElMessageBox.alert('列设置功能待实现', '提示', {
    confirmButtonText: '确定'
  })
  ElNotification({
    title: '列设置',
    message: '自定义列显示设置',
    type: 'info',
    duration: 2000
  })
}

// 处理智能提醒点击
const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
  // 可以根据提醒类型执行不同的操作
  switch (alert.type) {
    case 'lowStock':
      // 可以跳转到低库存筛选
      queryParams.status = 'warning'
      handleSearch()
      break
    case 'overStock':
      // 可以跳转到积压库存筛选
      ElMessage.info('已筛选显示积压库存')
      break
    case 'inactive':
      // 可以跳转到长期未动销商品筛选
      ElMessage.info('已筛选显示长期未动销商品')
      break
  }
}

// 生命周期
onMounted(() => {
  loadInventory()
  // ElNotification({
  //   title: '欢迎',
  //   message: '库存管理页面加载完成',
  //   type: 'success',
  //   duration: 3000
  // })
})
</script>

<style scoped lang="scss">
.inventory-management {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
}
</style>